package com.zcsy.manage.web.system;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.zcsy.commons.constants.Constants;
import com.zcsy.commons.constants.OwnerConstants;
import com.zcsy.commons.model.RequestConstants;
import com.zcsy.commons.model.RequestJson;
import com.zcsy.commons.sms.dlife.DlifeSmsConfig;
import com.zcsy.commons.util.DateUtils;
import com.zcsy.manage.model.base.CellInfo;
import com.zcsy.manage.model.system.User;
import com.zcsy.manage.service.base.ICommonConfigService;
import com.zcsy.manage.service.base.IVerifyCodeService;
import com.zcsy.manage.service.mall.IIntegralConfigService;
import com.zcsy.manage.service.mall.IIntegralRecordService;
import com.zcsy.manage.service.system.IUserService;
import com.zcsy.manage.web.common.SixCodeUtil;


/**
 * @ClassName: UserController
 * @Description: 用户控制层管理类
 * @author xujl 850789178@qq.com
 * @date 2016年1月8日
 */
@Controller
@RequestMapping(value = "/user")
public class UserController {
    
    @Autowired
    private IUserService userService;
    
    @Autowired
    private IVerifyCodeService verifyCodeService;
    
    @Autowired
    private ICommonConfigService commonConfigService;
    
    @Autowired
    private IIntegralRecordService integralRecordService;
    
    @Autowired
    private IIntegralConfigService IntegralConfigService;
    
    private static final int USER_CHECK = 1;
    private static final int PHONE_BIND = 2;
    
    /**
     * 重置密码
     * 
     * @param id	用户ID
     * @param lname	登录名
     * @param pwd	密码
     * @param request
     * @return
     */
    @RequestMapping(value = "resetPwd", method = RequestMethod.POST)
    @ResponseBody
    public RequestJson resetPwd(String id, String lname ,  String pwd , HttpServletRequest request) {
        RequestJson result = new RequestJson();
        User userVo = userService.selectByPrimaryKey(id);
        
        try {
        	userVo.setPwd(pwd);
            userVo.setModifydatetime(DateUtils.gettimestamp());
            userService.updateByPrimaryKeySelective(userVo);
            result.setSuccess(true);
        } catch (Exception e) {
            result.setSuccess(false);
            result.setMsg("操作失败");
        }
        return result;
    }

    /**
     * @Description 修改用户密码
     * @param id 用户id
     * @return 跳转页面url
     * @author liuying 1075817474@qq.com
     * @date 2016年5月11日
     * @see 
     */
    @RequestMapping(value = "changePassword", method = RequestMethod.GET)
	public String changePassword(Model model, String id) {
		try {
			if (!String.valueOf(Constants.STATE_DISABLED).equals(id)) {
				User userVo = userService.selectByPrimaryKey(id);
				model.addAttribute("user", userVo);
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
		return "common/changePassword";
	}
    
    /**
     * @Description 保存密码
     * @param id 主键id
     * @param uname 用户名
     * @param oldPwd 当前密码
     * @param newPwd 新密码
     * @param req 用户请求
     * @return 响应结果
     * @author liuying 1075817474@qq.com
     * @date 2016年5月12日
     * @see 
     */
    @RequestMapping(value = "savePassword", method = RequestMethod.GET)
    @ResponseBody
    public RequestJson savePassword(String id, String lname, String oldPwd, String newPwd, HttpServletRequest req) {
        RequestJson result = new RequestJson();
        try {
            //校验的用户对象
        	final User user = userService.selectByPrimaryKey(id);
        	
        	/*//更新密码的用户对象
            User userVo = new User();
            */
            //生成密匙
//        	final String oldUserKey = MD5Util.generalPassword(lname, oldPwd);
//        	final String newUserKey = MD5Util.generalPassword(lname, newPwd);
        	
        	//密码校验
			if(oldPwd.equals(user.getPwd())){
	        	/*userVo.setId(id);*/
	        	user.setPwd(newPwd);
	            userService.updateByPrimaryKeySelective(user);
	            result.setSuccess(true);
	            result.setMsg("操作成功");
			}else{
				result.setMsg("密码错误");
				result.setSuccess(false);
			}
        } catch (Exception e) {
            result.setSuccess(false);
            result.setMsg("操作失败");
            e.printStackTrace();
        }
        return result;
    }
    
    /**
     * @Description 跳转个人信息
     * @param id 用户id
     * @return 跳转页面url
     * @author yangfan 373188993@qq.com
     * @date 2016年8月1日
     * @see 
     */
    @RequestMapping(value = "changePersonInfo", method = RequestMethod.GET)
    public String changePersonalInfo(Model model, String id, HttpServletRequest req) {
        try {
        	
            if (!String.valueOf(Constants.STATE_DISABLED).equals(id)) {
                User user = userService.selectByPrimaryKey(id);
                model.addAttribute("user", user);
                
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return "common/changePersonInfo";
    }
    
    /**
     * @Description 保存个人信息,以及获得积分
     * @param id 用户id
     *        nickName 昵称
     *        userName 真实姓名
     *        sex 性别
     *        email 邮箱
     * @return result
     * @author yangfan 373188993@qq.com
     * @date 2016年8月1日
     * @see 
     */
    @RequestMapping(value = "savePersonInfo", method = RequestMethod.POST)
    @ResponseBody
    public RequestJson savePersonInfo(String id ,String nickName ,String userName, String email,Integer sex) {
        
        RequestJson result = new RequestJson();

        try {
            User user = userService.selectByPrimaryKey(id);
            /*user.setId(id);*/
            user.setNickname(nickName);
            user.setUsername(userName);
            user.setEmail(email);
            user.setSex(sex);
            if (null != id) {
                int flag = userService.updateByPrimaryKeySelective(user);
                if(flag == OwnerConstants.UPDATE_SUCCESS){
                    result.setSuccess(true);
                    result.setMsg("修改成功！");
                } else {
                    result.setSuccess(false);
                    result.setMsg("操作异常！");
                }
            }
            /*
            /**************************************用户完善个人资料，获得积分10**********************************
            //（！！！！！还要加判断，判断修改的用户信息资料是哪一项，判断是否已经加过分了！！！）
            //获取当前登陆的用户的信息
            User userVo = userService.selectByPrimaryKey(id);
            userId = userVo.getId();
            //根据唯一标识name获取小区积分配置对象
            CommonConfig commonConfig = commonConfigService.getByName("mall_integral_config");
            //"完善个人信息"可获得的积分值
            Integer integralOfPersonalInformation = IntegralConfigService.getIntegralValue("");
           //用户当天可加积分之和的上限
            Integer maxValuePerDay = commonConfigService.getIntegralMaxValueOfCell("mall_integral_config");
              //获取用户当天积分变动之和
            Integer soFarIntegralSum = integralRecordService.getIntegralOfToday(userId);
            
            // new一个积分变动记录
            IntegralRecord integralRecord = new IntegralRecord();

            //验证小区配置的积分上限值不为空以及值得有效性
            if (commonConfig != null && commonConfig.getValue().matches("[0-9]+")) {

                // 用户当天可加积分之和的上限
                Integer maxValuePerDay = Integer.valueOf(commonConfig.getValue());
                
                //当日积分上限 > 完善个人资料获得的积分 && 当天的积分变动值之和 <（积分上限-完善个人资料获得的积分）
                if (maxValuePerDay > integralOfPersonalInformation && soFarIntegralSum < (maxValuePerDay - integralOfPersonalInformation)) {
                    //插入积分，并且用户还可以继续获得积分！
                    userVo.setIntegral(userVo.getIntegral() + integralOfPersonalInformation);
                    userService.updateByPrimaryKeySelective(userVo);
                    
                    // 插入积分变更信息
                    integralRecordService.changeIntegralMethod(userId, "");
                    result.setMsg("完善个人资料成功获得10个积分！");
                }
                
                //用户当日变动的积值之和 == 积分上限
                if (soFarIntegralSum == maxValuePerDay) {
                    result.setMsg("已达今日累加积分上限");
                }
                //用户当日变动积分值之和 < 积分上限 && 用户当日变动积分值之和 >(积分上限-完善个人资料获得的积分)
                if (soFarIntegralSum < maxValuePerDay && soFarIntegralSum > (maxValuePerDay - integralOfPersonalInformation)) {
                    //获得积分，但是提示用户，今天已经不能继续获得积分了。。。
                    userVo.setIntegral(userVo.getIntegral() + maxValuePerDay - soFarIntegralSum);
                    userService.updateByPrimaryKeySelective(userVo);
                    
                    // 插入积分变更信息
                    integralRecordService.changeIntegralWhenToMaxValuePerDay(userId, "",maxValuePerDay - soFarIntegralSum);
                    result.setMsg("完善个人资料成功获得10个积分！，但是已达今日累积积分上限！");
                }
            }*/
            
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
    /**
     * @description 检查用户是否绑定了手机
     * @author chenxin
     * @date 2016年8月15日下午3:21:55
     */
    @RequestMapping(value = "userCheck", method = RequestMethod.GET)
    public String userCheck(Model model, HttpServletRequest req) {
        try {
            User user = (User)req.getSession().getAttribute(RequestConstants.USER_SESSION_ID);
            User userInfo = userService.selectByLoginName(user.getLoginname());
            model.addAttribute("user", userInfo);
            String phone = userInfo.getPhone();
                if(StringUtils.isNotEmpty(phone)){
                	model.addAttribute("type", USER_CHECK);
                } else {
                    model.addAttribute("type", PHONE_BIND); 
                }
        } catch (Exception e) {
            e.printStackTrace();
        }
        
        model.addAttribute("resendTime", DlifeSmsConfig.SMS_RESEND_TIME);
        
        return "bindphone/bindPhone";
        
    }
    
    /**
     * @description 给旧手机发送验证码
     * @author chenxin
     * @date 2016年8月15日下午4:49:51
     */
    @RequestMapping(value = "sendOldPhone", method = RequestMethod.POST)
    @ResponseBody
    public RequestJson sendMSG(HttpServletRequest req){
        RequestJson result = new RequestJson();
        try{
             User user = (User)req.getSession().getAttribute(RequestConstants.USER_SESSION_ID);
             User userInfo = userService.selectByLoginName(user.getLoginname());
             String phone = userInfo.getPhone();
             //随机生成六位数验证码
             String phoneCode = SixCodeUtil.sixCode();
             
             user.setUserType(Constants.BUSINESS_TYPE);
             verifyCodeService.sendCodeMessage(userInfo, phone, phoneCode, result);
             
        }  catch (Exception e) {
             result.setSuccess(false);
             result.setMsg("操作失败");
        }
        
        return result;
        
    }
    
    /**
     * @description 给新手机发送验证码
     * @author chenxin
     * @date 2016年8月15日下午4:55:06
     */
    @RequestMapping(value = "sendNewPhone", method = RequestMethod.POST)
    @ResponseBody
    public RequestJson savaPhone(String phone, String id, HttpServletRequest req) {
        RequestJson result = new RequestJson();
        try{
            User user = (User)req.getSession().getAttribute(RequestConstants.USER_SESSION_ID);
            User userInfo = userService.selectByLoginName(user.getLoginname());
            //随机生成六位数验证码
            String phoneCode = SixCodeUtil.sixCode();
            user.setUserType(Constants.OWNER_TYPE);
            verifyCodeService.sendCodeMessage(userInfo, phone, phoneCode, result);
            
        } catch (Exception e) {
            e.printStackTrace();
            result.setSuccess(false);
            result.setMsg("操作失败");
        }
        
        return result;
    }
    
    /**
     * @description  返回绑定手机页面
     * @author chenxin
     * @date 2016年8月15日下午5:02:40
     */
    @RequestMapping(value = "bindPhone", method = RequestMethod.GET)
    public String bindPhone(Model model, HttpServletRequest req) {
        model.addAttribute("type", PHONE_BIND);
        model.addAttribute("resendTime", DlifeSmsConfig.SMS_RESEND_TIME);
        
        return "bindphone/bindPhone";
        
    }
    
  
//    /**
//     * @description 返回手机绑定完成页面
//     * @author chenxin
//     * @date 2016年8月15日下午5:02:20
//     */
//    @RequestMapping(value = "bindComplete", method = RequestMethod.GET)
//    public String bindComplete(Model model, String newPhone, HttpServletRequest req) {
//        model.addAttribute("type", PHONE_BIND);
//        model.addAttribute("newPhone", newPhone);
//        
//        return "bindphone/bindComplete";
//    }
    
    /**
     * @Description:保存更改手机号
     * @param model
     * @param req
     * @return 返回手机绑定完成页面
     * @author huangls 1449700087@qq.com
     * @date 2016年9月9日
     */
    @RequestMapping(value = "savePhone", method = RequestMethod.GET)
    public String savePhone(Model model, String newPhone, HttpServletRequest req) {
    	
    	try{
	    	User user = (User)req.getSession().getAttribute(RequestConstants.USER_SESSION_ID);
	        User userInfo = userService.selectByLoginName(user.getLoginname());
	        userInfo.setPhone(newPhone);
	        userService.updateByPrimaryKeySelective(userInfo);
	        
	        model.addAttribute("userInfo", userInfo);
	       
    	} catch (Exception e) {
    		e.printStackTrace();
    	}
//    	model.addAttribute("resendTime", DlifeSmsConfig.SMS_RESEND_TIME);
    	model.addAttribute("type", PHONE_BIND);
    	return "bindphone/bindComplete";
    } 
}
